package com.libgdxbar.pvzlikegame.screens.gamescreens;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.utils.ScreenUtils;
import com.libgdxbar.pvzlikegame.entities.EntityGroup;
import com.libgdxbar.pvzlikegame.objects.TextureSplashLogo;
import com.libgdxbar.pvzlikegame.screens.GameScreenAdapter;
import com.libgdxbar.pvzlikegame.screens.screenkeys.ExampleScreenKey;
import com.libgdxbar.pvzlikegame.screens.screenkeys.MainScreenKey;
import com.libgdxbar.pvzlikegame.screens.screenkeys.ScreenKey;

public class SplashScreen extends GameScreenAdapter {
	private EntityGroup entities;
	private TextureSplashLogo logo;
	private SplashSimpleAnim anim;

	@Override
	public ScreenKey getScreenKey() {
		return MainScreenKey.SplashScreen;
	}

	@Override
	protected void initViewport() {
		setViewport(640, 480);
	}

	@Override
	public void create() {
		entities = EntityGroup.getInstance();
		logo = new TextureSplashLogo();
		logo.setScl(1, 1);
		logo.setCenterPosition(getViewCenter().x, getViewCenter().y);
		anim = new SplashSimpleAnim();
		anim.onCompleted = () -> {
			screenManager.setCurScreen(ExampleScreenKey.ShapeAndTextureEntityExample);
		};
	}

	@Override
	public void render(float delta) {
		ScreenUtils.clear(0f, 0f, 0f, 1f);

		entities.update(delta);

		Batch batch = entities.batch;
		Color color = batch.getColor();
		float oldA = color.a;
		color.a = anim.step(delta);
		batch.setColor(color);

		entities.render(getViewport().getCamera());

		color.a = oldA;
		batch.setColor(color);
	}

	@Override
	public void show() {
		super.show();
		anim.reset();
		entities.add(logo);
	}

	@Override
	public void hide() {
		super.hide();
		entities.remove(logo);
	}

	@Override
	public void dispose() {
		if (logo != null) logo.dispose();
	}


	static class SplashSimpleAnim {
		float duration = 2;//秒
		float t;
		float startR = 1;
		float endR = 0.2f;
		Runnable onCompleted;

		public float step(float delta) {
			t += delta;

			float normalTime = t / duration;
			float interpolation = lerp(startR, endR, normalTime);
			if (normalTime > 1) onCompleted.run();
			return interpolation;
		}

		public void reset() {
			t = 0;
		}

		public float lerp(float a, float b, float t) {
			return a + (b - a) * t;
		}
	}
}
